package com.yt.fras.utils;

import com.yt.fras.pojo.model.Location;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName:LocationUtil
 * Package:com.yt.fras.utils
 * Description:
 *
 * @date:2021/11/2 0:25
 * @author:yt
 */
@Component
public class LocationUtil {

    private static String URL = "https://restapi.amap.com/v5/ip?key={key}&type=4&ip={ip}";
    private static String key = "f79e755a42399d2113c864c21dc35454";
    private RestTemplate restTemplate;

    public LocationUtil() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(3 * 1000);
        factory.setConnectTimeout(3 * 1000);
        this.restTemplate = new RestTemplate(factory);
    }

    public Location getIpLocation(String ip) {
        Map<String, String> params = new HashMap<>();
        params.put("key", key);
        params.put("ip", ip);
        ResponseEntity<Location> result = restTemplate.getForEntity(URL, Location.class, params);
        if (result.getBody() == null) {
            return null;
        }
        System.out.println(result.getBody());
        return result.getBody();
    }

}
